package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private WebSocketServer webSocketServer;
//    @Autowired
//    private UserMapper userMapper;
@Autowired
private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO)
    {
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        Long userId= BaseContext.getCurrentId();//当前用户id
        //不要相信前端传来的数据：这两种情况是无法下单的
        //1判断地址簿id是否为null
        if (null==ordersSubmitDTO.getAddressBookId())
        {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断这个人的购物车数据是否为空
        List<ShoppingCart> shoppingcartlist = shoppingCartMapper.list(userId);
        if(shoppingcartlist == null|| shoppingcartlist.size()==0)//如果为空，抛出异常
        {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
//         构造order对象插入到订单表
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        //13个属性需要补全（但是有几个属性没法写）
        order.setUserId(BaseContext.getCurrentId());
        order.setNumber(String.valueOf(System.currentTimeMillis()));//订单号直接就是当前时间的毫秒值
       order.setStatus(Orders.PENDING_PAYMENT);
       order.setPayStatus(Orders.UN_PAID);
       order.setOrderTime(LocalDateTime.now());
//        order.setCancelTime();
//    order.setRejectionReason();
//       order.setCancelReason();
//       order.setCheckoutTime(LocalDateTime.now());结账时间，等结账的时候肯定会设置的，现在起码我无从设置
        AddressBook addressbook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        order.setConsignee(addressbook.getConsignee());
        order.setPhone(addressbook.getPhone());
        order.setAddress(addressbook.getProvinceName()+addressbook.getCityName()+addressbook.getDetail());
     //   order.setUserName();//用户名不知道写什么？
        orderMapper.insert(order);

        //插入订单明细表   一个商品（一个套餐/一个菜品）对应一条数据，那我的购物车表不就是一个商品（一个套餐/一个菜品）对应一条数据


//        OrderDetail orderDetail = new OrderDetail();

List<OrderDetail> orderDetailList = new ArrayList<>();

   //遍历一下购物车表
//        System.out.println("****************");
//        for(ShoppingCart shoppingCart : shoppingcartlist)
//        {
//            System.out.println(shoppingCart);
//        }
//        System.out.println("****************");
        //查询这个人的购物车信息，我要拿到这个人的mai的商品的信息（份数）
        for (ShoppingCart shoppingCart : shoppingcartlist)
        {  OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getId());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setName(shoppingCart.getName());
//            System.out.println(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetailList.add(orderDetail);
        }
//        System.out.println("****************");
//        //遍历一下orderDetailList每个对象的所有属性
//        for(OrderDetail od : orderDetailList)
//        {
//            System.out.println(od);
//        }
//        System.out.println("****************");
        orderDetailMapper.insertBatch(orderDetailList);
   //已经把购物车数据插入到订单明细表了，现在需要把购物车表清空，因为已经下单了，购物车里已经没有东西了
        shoppingCartMapper.clean(userId);
        orderSubmitVO= orderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return  orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;

        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

        //生成空JSON，跳过微信支付流程
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
/*      // 模拟支付成功，更新数据库订单状态
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);*/

        return vo;


    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        Map map=new HashMap();
        map.put("type",1);//1用户端支付好了，作为来单提醒2是用户端催促订单，自己要转发给管理端（客户端）
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号为："+ordersDB.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    @Override
    public void cancel(Long orderId) {
        log.info("订单取消：{}", orderId);
        orderMapper.deleteById(orderId);
        orderDetailMapper.deleteByOrderId(orderId);
    }

    @Override
    public PageResult page(Integer page, Integer pageSize, Integer status)
    {//根据返回信息来说，我需要查订单明细表（封装到集合中）和订单表

        OrdersPageQueryDTO ordersPageQueryDTO=new OrdersPageQueryDTO();
          ordersPageQueryDTO.setStatus(status);
          ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());//这里是当前登录用户的id*****


        PageResult pageResult=new PageResult();

        List<OrderVO> orderVOList=new ArrayList<>();
        PageHelper.startPage(page,pageSize);
        Page<Orders> orderList= orderMapper.page(ordersPageQueryDTO);//根据用户id和订单状态查询订单
        for(Orders order:orderList)
        {
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
            orderVO.setOrderDetailList(orderDetailMapper.getByOrderId(order.getId()));
            orderVOList.add(orderVO);
        }
//         pageResult.setTotal(orderVOList.size());
         pageResult.setTotal(orderList.getTotal());
        pageResult.setRecords(orderVOList);
        System.out.println("orderList："+orderList.getTotal());
        System.out.println("orderVOList："+orderVOList.size());

//         Page<Orders> OrdersList =orderMapper.page(status,userId);//我感觉这里是对当前查询进行limit操作
//        List<Orders> OrdersList =orderMapper.page(status,userId);
//        for(Orders order: OrdersList)
//        {
//            order.setOrderDetails(orderDetailMapper.getByOrderId(order.getId()));
//        }
//           Page result=new Page();
        //把分页数据填充到result中
//      result=OrdersList;


//         Orders order=orderMapper.getByUserId(userId);
//        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());

        return pageResult;


    }

    @Override
    public List<OrderDetail> getOrderDetailByOrderId(Long id)
    {
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        return orderDetailList;
    }

    @Override
    public void repetition(Long id) {
        Long userId = BaseContext.getCurrentId();//拿到当前用户的主键id
        //因为我这里的购物车已经被清楚干净了，所以我只能在订单明细表去找到所有的商品信息，尝试转化到购物车中。订单表跟该订单商品没有一点关系，全是订单号，订单日期，支付方式，也就是订单本体等等
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);//拿到了本userid的所有商品信息，尝试转化到购物车表中
        List<ShoppingCart> shoppingCartList=new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList )
        {
            ShoppingCart shoppingCart=new ShoppingCart();
            shoppingCart.setUserId(userId); //我要往购物车表插入数据，这个你总要设置一下吧
            shoppingCart.setCreateTime(LocalDateTime.now());
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCartList.add(shoppingCart);
        }

        if(shoppingCartList!=null && shoppingCartList.size()>0)shoppingCartMapper.insertBatch(shoppingCartList);
        else throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
    }

    @Override
    public void confirm(Long id) {
        Orders orders=new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        if (orders==null)return;
        if(orders.getStatus()!=Orders.TO_BE_CONFIRMED)
        {
             throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if(orders.getPayStatus()==Orders.PAID)
        {
            //调用微信官方接口实现退款
        }
        Orders order = Orders.builder()
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .build();
        orderMapper.update(order);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO)
    {
        log.info("订单取消：{}", ordersCancelDTO.getId());
        //判断该订单是否已付款
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if(orders.getPayStatus()==Orders.PAID)
        {
            //调用微信官方接口实现退款
        }
        Orders order = Orders.builder()
                .cancelReason(ordersCancelDTO.getCancelReason())
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .build();
        orderMapper.update(order);
    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed( orderMapper.countConfirmedStatus());
        orderStatisticsVO.setDeliveryInProgress(orderMapper.countDeliveryInProgressStatus());
        orderStatisticsVO.setToBeConfirmed( orderMapper.countToBeConfirmedStatus());
        return orderStatisticsVO;
    }

    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
            PageResult pageResult=new PageResult();
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage=orderMapper.page(ordersPageQueryDTO);
        pageResult.setTotal(ordersPage.getTotal());
        pageResult.setRecords(ordersPage.getResult());
        return pageResult;
    }

    @Override
    public void delivery(Long id)
    {
        Orders order = Orders.builder()
                .status(Orders.DELIVERY_IN_PROGRESS)
                .id(id)
                .build();
        orderMapper.update(order);

    }
    @Override
    public void complete(Long id)
    {
        Orders order = Orders.builder()
                .status(Orders.COMPLETED)
                .id(id)
                .build();
        orderMapper.update(order);

    }

    @Override
    public OrderVO getById(Long id) {
        OrderVO orderVO=new OrderVO();
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        String CommodityInformation ="";
        for(OrderDetail orderDetail :orderDetailList )
        {
            CommodityInformation+=orderDetail.getName()+"  ";
        }
        if(orders!=null)
        {

            BeanUtils.copyProperties(orders,orderVO);//orderVO继承了orders，他这个子类包含父类的所有属性
            orderVO.setOrderDetailList(orderDetailList);
            orderVO.setOrderDishes(CommodityInformation);
            return orderVO;
        }
        return orderVO;
    }

    @Override
    public void reminder(Long id)
    {
        Orders ordersDB = orderMapper.getById(id);
        if(ordersDB ==null)
        {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map=new HashMap();
        map.put("type",2);//1用户端支付好了，作为来单提醒      2是用户端催促订单(商家一直不接单)，自己要转发给管理端（客户端）
        map.put("orderId",id);
        map.put("content","订单号为："+ ordersDB.getNumber());

        //向已经连接的客户端（用户端）发送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}
